package cn.lili.controller.order;

import cn.lili.common.enums.ResultCode;
import cn.lili.common.enums.ResultUtil;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.AuthUser;
import cn.lili.common.security.OperationalJudgment;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.utils.CurrencyUtil;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.member.entity.dos.Member;
import cn.lili.modules.member.entity.dos.MemberEvaluation;
import cn.lili.modules.member.service.EextensionService;
import cn.lili.modules.member.service.MemberEvaluationService;
import cn.lili.modules.order.order.entity.dos.Order;
import cn.lili.modules.order.order.entity.dto.OrderSearchParams;
import cn.lili.modules.order.order.entity.enums.OrderStatusEnum;
import cn.lili.modules.order.order.entity.vo.OrderDetailVO;
import cn.lili.modules.order.order.entity.vo.OrderSimpleVO;
import cn.lili.modules.order.order.entity.vo.OrderVO;
import cn.lili.modules.order.order.service.OrderService;
import cn.lili.modules.store.entity.dos.Store;
import cn.lili.modules.store.service.StoreService;
import cn.lili.modules.wallet.entity.dos.MemberWallet;
import cn.lili.modules.wallet.entity.dos.WalletLogDetail;
import cn.lili.modules.wallet.entity.dto.MemberWalletUpdateDTO;
import cn.lili.modules.wallet.entity.enums.DepositServiceTypeEnum;
import cn.lili.modules.wallet.entity.enums.WalletOwnerEnum;
import cn.lili.modules.wallet.service.MemberWalletService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Objects;

/**
 * 买家端,订单接口
 *
 * @author Chopper
 * @since 2020/11/16 10:08 下午
 */
@RestController
@Api(tags = "买家端,订单接口")
@RequestMapping("/buyer/orders")
public class OrderBuyerController {

	/**
	 * 订单
	 */
	@Autowired
	private OrderService orderService;

	@Autowired
	private MemberWalletService memberWalletService;
	@Autowired
	private StoreService storeService;

	@Autowired
	private MemberEvaluationService memberEvaluationService;

	@Autowired
	private EextensionService eextensionService;

	@ApiOperation(value = "查询会员订单列表")
	@GetMapping
	public ResultMessage<IPage<OrderSimpleVO>> queryMineOrder(OrderSearchParams orderSearchParams) {
		AuthUser currentUser = Objects.requireNonNull(UserContext.getCurrentUser());
		orderSearchParams.setMemberId(currentUser.getId());

		eextensionService.tempExToEx(currentUser.getId(), true);
		return ResultUtil.data(orderService.queryByParams(orderSearchParams));
	}

	@ApiOperation(value = "订单明细")
	@ApiImplicitParams({@ApiImplicitParam(name = "orderSn", value = "订单编号", required = true, paramType = "path")})
	@RequestMapping(value = "/{orderSn}")
	public ResultMessage<OrderDetailVO> detail(@NotNull(message = "订单编号不能为空") @PathVariable("orderSn") String orderSn) {
		OrderDetailVO orderDetailVO = orderService.queryDetail(orderSn);
		OperationalJudgment.judgment(orderDetailVO.getOrder());
		return ResultUtil.data(orderDetailVO);
	}

	@ApiOperation(value = "订单明细")
	@ApiImplicitParams({@ApiImplicitParam(name = "orderNo", value = "订单编号", required = true, paramType = "path"),
			@ApiImplicitParam(name = "goodsId", value = "商品编号", required = true, paramType = "path")})
	@RequestMapping(value = "/comment/{orderNo}/{goodsId}")
	public ResultMessage<MemberEvaluation> comment(
			@NotNull(message = "订单编号不能为空") @PathVariable("orderNo") String orderNo,
			@NotNull(message = "商品编号不能为空") @PathVariable("goodsId") String goodsId) {
		LambdaQueryWrapper<MemberEvaluation> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(MemberEvaluation::getOrderNo, orderNo);
		queryWrapper.eq(MemberEvaluation::getGoodsId, goodsId);
		MemberEvaluation memberEvaluation = memberEvaluationService.getOne(queryWrapper);
		return ResultUtil.data(memberEvaluation);
	}

	@ApiOperation(value = "确认收货")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "orderSn", value = "订单编号", required = true, dataType = "String", paramType = "path"),
			@ApiImplicitParam(name = "paymentPassword", value = "支付密码", required = true, dataType = "String", paramType = "query")})
	@RequestMapping(value = "/{orderSn}/receiving")
	public ResultMessage<Object> receiving(@ApiIgnore @PathVariable("orderSn") String orderSn,
			@RequestParam("paymentPassword") String paymentPassword) {
		Order order = orderService.getBySn(orderSn);
		// 通过memberid查询会员支付密码
		Member member = orderService.getMemberInfo(order.getMemberId());
		if (member == null) {
			throw new ServiceException("会员信息查询失败");
		}
		if (order == null) {
			throw new ServiceException(ResultCode.ORDER_NOT_EXIST);
		}
		// 判定是否是待收货状态
		if (!order.getOrderStatus().equals(OrderStatusEnum.DELIVERED.name())) {
			throw new ServiceException(ResultCode.ORDER_DELIVERED_ERROR);
		}
		// 设置免密后跳过支付密码验证
		if (0 == member.getNoSecret()) {
			// 比对密码是否正确
			if (!new BCryptPasswordEncoder().matches(paymentPassword, member.getPaymentPassword())) {
				throw new ServiceException(ResultCode.PAY_PASSWORD_ERROR);
			}
		}
		orderService.complete(orderSn);
		return ResultUtil.success();
	}

	@ApiOperation(value = "取消订单")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "orderSn", value = "订单编号", required = true, dataType = "String", paramType = "path"),
			@ApiImplicitParam(name = "reason", value = "取消原因", required = true, dataType = "String", paramType = "query")})
	@RequestMapping(value = "/{orderSn}/cancel")
	public ResultMessage<Object> cancel(@ApiIgnore @PathVariable String orderSn, @RequestParam String reason) {
		orderService.cancel(orderSn, reason);
		return ResultUtil.success();
	}

	@ApiOperation(value = "删除订单")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "orderSn", value = "订单编号", required = true, dataType = "String", paramType = "path")})
	@DeleteMapping(value = "/{orderSn}")
	public ResultMessage<Object> deleteOrder(@PathVariable String orderSn) {
		OperationalJudgment.judgment(orderService.getBySn(orderSn));
		orderService.deleteOrder(orderSn);
		return ResultUtil.success();
	}

	@ApiOperation(value = "查询物流踪迹")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "orderSn", value = "订单编号", required = true, dataType = "String", paramType = "path")})
	@RequestMapping(value = "/getTraces/{orderSn}")
	public ResultMessage<Object> getTraces(@NotBlank(message = "订单编号不能为空") @PathVariable String orderSn) {
		OperationalJudgment.judgment(orderService.getBySn(orderSn));
		return ResultUtil.data(orderService.getTraces(orderSn));
	}

	@ApiOperation(value = "开票")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "orderSn", value = "订单编号", required = true, dataType = "String", paramType = "path")})
	@RequestMapping(value = "/receipt/{orderSn}")
	public ResultMessage<Object> invoice(@NotBlank(message = "订单编号不能为空") @PathVariable String orderSn) {
		OperationalJudgment.judgment(orderService.getBySn(orderSn));
		return ResultUtil.data(orderService.invoice(orderSn));
	}

	@ApiOperation(value = "滚动消息")
	@RequestMapping(value = "/news")
	public ResultMessage<List<OrderSimpleVO>> news() {
		return ResultUtil.data(orderService.findAll());
	}

	@ApiOperation(value = "根据核验码获取订单信息")
	@ApiImplicitParam(name = "verificationCode", value = "核验码", required = true, paramType = "path")
	@RequestMapping(value = "/getOrderByVerificationCode/{verificationCode}")
	public ResultMessage<Object> getOrderByVerificationCode(@PathVariable String verificationCode) {
		return ResultUtil.data(orderService.getOrderByVerificationCode(verificationCode));
	}

	@ApiOperation(value = "订单核验")
	@ApiImplicitParams({@ApiImplicitParam(name = "orderSn", value = "订单号", required = true, paramType = "path"),
			@ApiImplicitParam(name = "verificationCode", value = "核验码", required = true, paramType = "path")})
	@PutMapping(value = "/take/{orderSn}/{verificationCode}")
	public ResultMessage<Object> take(@PathVariable String orderSn, @PathVariable String verificationCode) {
		return ResultUtil.data(orderService.take(orderSn, verificationCode));
	}

}
